package com.clouddisk.file.chain.impl;

import com.clouddisk.common.exception.BusinessException;
import com.clouddisk.file.chain.FileOperationHandler;
import com.clouddisk.file.chain.FileOperationContext;
import com.clouddisk.file.mapper.FileMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

@Component
@RequiredArgsConstructor
public class FileNameHandler implements FileOperationHandler {

    private final FileMapper fileMapper;
    private FileOperationHandler next;

    @Override
    public void handle(FileOperationContext context) {
        if (!context.isShouldContinue()) {
            return;
        }

        String fileName = handleFileName(context.getUploadDTO().getFile().getOriginalFilename());
        
        // 检查文件名是否已存在
        if (fileMapper.checkFileNameExists(context.getUserId(), context.getUploadDTO().getParentId(), fileName) > 0) {
            fileName = generateUniqueFileName(context.getUserId(), context.getUploadDTO().getParentId(), fileName);
        }

        context.setFileName(fileName);

        if (next != null) {
            next.handle(context);
        }
    }

    @Override
    public void setNext(FileOperationHandler next) {
        this.next = next;
    }

    /**
     * 处理文件名
     */
    private String handleFileName(String fileName) {
        if (fileName == null || fileName.trim().isEmpty()) {
            throw new BusinessException("文件名不能为空");
        }

        // 去除首尾空格
        fileName = fileName.trim();

        // 替换特殊字符
        fileName = fileName.replaceAll("[\\\\/:*?\"<>|]", "_");

        // 截断过长的文件名(保留扩展名)
        int maxLength = 255;
        if (fileName.length() > maxLength) {
            int extensionIndex = fileName.lastIndexOf('.');
            if (extensionIndex > 0) {
                String extension = fileName.substring(extensionIndex);
                fileName = fileName.substring(0, maxLength - extension.length()) + extension;
            } else {
                fileName = fileName.substring(0, maxLength);
            }
        }

        return fileName;
    }

    /**
     * 生成唯一文件名
     */
    private String generateUniqueFileName(Long userId, Long parentId, String fileName) {
        String nameWithoutExtension;
        String extension;
        int extensionIndex = fileName.lastIndexOf('.');
        if (extensionIndex > 0) {
            nameWithoutExtension = fileName.substring(0, extensionIndex);
            extension = fileName.substring(extensionIndex);
        } else {
            nameWithoutExtension = fileName;
            extension = "";
        }

        int count = 1;
        String newFileName = fileName;
        while (fileMapper.checkFileNameExists(userId, parentId, newFileName) > 0) {
            newFileName = nameWithoutExtension + "(" + count + ")" + extension;
            count++;
        }
        return newFileName;
    }
} 